package com.service.approval.controller;

import java.io.BufferedReader;
import java.io.InputStreamReader;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import com.service.approval.controller.dto.ApprovalResult;
import com.service.approval.interceptor.ApprovalContext;
import com.service.approval.interceptor.ApprovalIntercepterChain;
import com.service.approval.service.ApprovalService;

@RestController
@RequestMapping("/")
public class ApprovalController {

	@Autowired
	private ApprovalIntercepterChain approvalIntercepterChain;
	@Autowired
	private ApprovalService approvalService;
	
	@RequestMapping("/approval")
	@ResponseBody
	public ApprovalResult approval(HttpServletRequest request) {
		try {
			// 获取核保信息
			String approvalSource = getApprovalSource(request);
			// 检查核保参数（执行拦截器）
			ApprovalContext approvalContext = new ApprovalContext(approvalSource);
			approvalIntercepterChain.executeIntercepter(approvalContext);
			//调用核保业务进行核保
			ApprovalResult approvalResult = approvalService.approval(approvalContext.getApprovalInfo());
			return approvalResult;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return new ApprovalResult(false, "核保失败！");
	}

	private String getApprovalSource(HttpServletRequest request) throws Exception {
		request.setCharacterEncoding("utf-8");
		BufferedReader br = new BufferedReader(new InputStreamReader(request.getInputStream(), "UTF-8"));
		String line = null;
		StringBuilder sb = new StringBuilder();
		while ((line = br.readLine()) != null) {
			sb.append(line);
		}
		if (sb == null || sb.toString().trim().equals("")) {
			throw new Exception("核保请求参数为空！");
		}
		return sb.toString();
	}
}
